package com.cardone.common.util;

import java.util.Comparator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.cardone.common.Characters;
import com.cardone.context.function.Execution0Function;
import com.google.common.collect.Table;

/**
 * collection 工具
 *
 * @author yaohaitao
 *
 */
public class CollectionUtils {
	private static int padLength = Integer.MAX_VALUE - 1000;

	/**
	 * 复制属性
	 *
	 * @param sources
	 *          源对象
	 * @param targets
	 *          目标对象
	 * @param targetFunction
	 *          目标对象
	 * @param parameters
	 */
	public static <S, T> void copyProperties(final List<S> sources, final List<T> targets, final Execution0Function<T> targetFunction, final Table<String, String, Object> parameters) {
		if (org.apache.commons.collections.CollectionUtils.isEmpty(sources)) {
			return;
		}

		if (targetFunction == null) {
			return;
		}

		for (int i = 0; i < sources.size(); i++) {
			if (targets.size() > i) {
				BeanUtils.copyProperties(sources.get(i), targets.get(i), parameters);

				continue;
			}

			final T target = targetFunction.execution();

			BeanUtils.copyProperties(sources.get(i), target, parameters);

			targets.add(target);
		}
	}

	/**
	 * 排序关于长度
	 *
	 * @param stringlist
	 *          字符串集合
	 */
	public static void sortForLength(final List<String> stringlist) {
		if (org.apache.commons.collections.CollectionUtils.isEmpty(stringlist)) {
			return;
		}

		java.util.Collections.sort(stringlist, new Comparator<String>() {
			@Override
			public int compare(final String s1, final String s2) {
				int s1Length = StringUtils.length(s1);

				if (StringUtils.contains(s1, Characters.meter.stringValue())) {
					s1Length = s1Length + CollectionUtils.padLength;
				}

				int s2Length = StringUtils.length(s2);

				if (StringUtils.contains(s2, Characters.meter.stringValue())) {
					s2Length = s2Length + CollectionUtils.padLength;
				}

				return s1Length - s2Length;
			}
		});
	}
}
